<template>
  <div class="base-table">
    <!-- 表格工具栏 -->
    <div
      class="table-toolbar"
      v-if="showToolbar"
    >
      <div class="toolbar-left">
        <slot name="toolbar-left"></slot>
      </div>
      <div class="toolbar-right">
        <ElTooltip
          :content="$t('elTableWrapper.toolsBar.refresh')"
          placement="top"
        >
          <ElButton
            :icon="Refresh"
            circle
            @click="handleRefresh"
          />
        </ElTooltip>

        <ElTooltip
          :content="$t('elTableWrapper.toolsBar.tableSize')"
          placement="top"
        >
          <ElDropdown
            trigger="click"
            @command="handleTableSizeChange"
          >
            <ElButton
              :icon="Grid"
              circle
            />
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem command="default">{{
                  $t('elTableWrapper.dropDownItem.default')
                }}</ElDropdownItem>
                <ElDropdownItem command="large">{{
                  $t('elTableWrapper.dropDownItem.large')
                }}</ElDropdownItem>
                <ElDropdownItem command="default">{{
                  $t('elTableWrapper.dropDownItem.medium')
                }}</ElDropdownItem>
                <ElDropdownItem command="small">{{
                  $t('elTableWrapper.dropDownItem.small')
                }}</ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </ElTooltip>
        <slot name="toolbar-right"></slot>
      </div>
    </div>

    <!-- 表格主体 -->
    <ElTable
      :key="currentLocale"
      :size="tableSize"
      ref="tableRef"
      v-bind="$attrs"
      :data="tableData"
      :border="border"
      :stripe="stripe"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <!-- 多选列 -->
      <ElTableColumn
        v-if="showSelection"
        type="selection"
        width="55"
        :align="'center'"
        fixed="left"
      />

      <!-- 索引列 -->
      <ElTableColumn
        v-if="showIndex"
        type="index"
        :label="$t('elTableWrapper.serialNumberC')"
        width="60"
        :align="'center'"
      />

      <!-- 动态列 -->
      <template
        v-for="column in columns"
        :key="column.prop"
      >
        <ElTableColumn v-bind="getColumnProps(column)">
          <!-- 自定义列头 -->
          <template
            #header="scope"
            v-if="column.headerSlot"
          >
            <slot
              :name="column.headerSlot"
              v-bind="scope"
            ></slot>
          </template>

          <!-- 自定义单元格 -->
          <template
            #default="scope"
            v-if="column.slot"
          >
            <slot
              :name="column.slot"
              v-bind="scope"
            ></slot>
          </template>

          <!-- 默认单元格渲染 -->
          <template
            #default="scope"
            v-else
          >
            {{ formatColumnValue(scope.row, column) }}
          </template>
        </ElTableColumn>
      </template>

      <!-- 操作列 -->
      <ElTableColumn
        v-if="$slots.action"
        :label="$t('elTableWrapper.operationC')"
        :width="actionWidth"
        :fixed="actionFixed"
        :align="'center'"
      >
        <template #default="scope">
          <slot
            name="action"
            v-bind="scope"
          ></slot>
        </template>
      </ElTableColumn>
    </ElTable>

    <!-- 分页 -->
    <div
      class="table-pagination"
      v-if="enablePagination"
    >
      <!-- <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        :layout="paginationLayout"
        :total="total"
        :background="true"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentChange"
      /> -->

      <ElPaginationWrapper
        v-model:page="currentPage"
        v-model:limit="pageSize"
        :total="total"
        @update:limit="handleSizeChange"
        @update:page="handleCurrentChange"
        @pagination="handlePaginationChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { Refresh, Grid } from '@element-plus/icons-vue'
  import type { TableColumnCtx } from 'element-plus'
  import type { TableColumn, TableItem, DefaultRow, TableProps } from '@/types/ui/elTableWrapper.ts'
  import { systemSettings } from '@/stores'
  import { T } from '@/utils/locales'

  const useSystemSettings = systemSettings()

  const { currentLocale } = storeToRefs(useSystemSettings)

  const props = withDefaults(defineProps<TableProps>(), {
    data: () => [],
    showSelection: false,
    showIndex: true,
    showToolbar: true,
    border: true,
    stripe: true,
    enablePagination: true,
    total: 0,
    page: 1,
    limit: 10,
    pageSizes: () => [10, 20, 50, 100],
    paginationLayout: 'total, sizes, prev, pager, next, jumper',
    loading: false,
    actionWidth: 150,
    actionFixed: 'right',
  })

  const emit = defineEmits<{
    'update:page': [page: number]
    'update:limit': [limit: number]
    'selection-change': [selection: TableItem[]]
    'sort-change': [sort: { prop: string; order: string }]
    refresh: []
    /** 分页改变时触发 */
    pagination: [params: { page: number; limit: number }]
  }>()

  type tableSizeType = '' | 'default' | 'large' | 'small'

  const tableSize = ref<tableSizeType>('')

  // 表格实例
  const tableRef = ref()
  // 当前页码
  const currentPage = ref(props.page)
  // 每页数量
  const pageSize = ref(props.limit)
  // 表格数据
  const tableData = computed(() => props.data)

  // 每页显示条数改变时触发
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    emit('update:limit', val)
  }

  // 当前页改变时触发
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    emit('update:page', val)
  }

  // 当前页改变时触发
  const handlePaginationChange = (params: { page: number; limit: number }) => {
    currentPage.value = params.page
    pageSize.value = params.limit
    emit('pagination', {
      page: params.page,
      limit: params.limit,
    })
  }

  // 处理多选变化
  const handleSelectionChange = (selection: TableItem[]) => {
    emit('selection-change', selection)
  }

  // 处理排序变化
  const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
    emit('sort-change', { prop, order })
  }

  // 处理刷新
  const handleRefresh = () => {
    emit('refresh')
  }

  // 处理表格密度变化
  const handleTableSizeChange = (size: tableSizeType) => {
    tableSize.value = size
  }

  // 获取列配置
  const getColumnProps = <T extends DefaultRow>(column: TableColumn<T>) => {
    const props = { ...column }
    // 移除自定义属性
    delete props.slot
    delete props.headerSlot
    props.label = T(props.label) || ''
    return props
  }

  // 格式化列值
  const formatColumnValue = <T extends DefaultRow>(row: TableItem<T>, column: TableColumn<T>) => {
    const value = row[column.prop]
    if (column.formatter) {
      return column.formatter(row, column as TableColumnCtx<T>, value, 0)
    }
    return value as string
  }

  // 暴露方法
  defineExpose({
    tableRef,
    ...tableRef.value,
  })
</script>

<style lang="scss" scoped>
  .base-table {
    background-color: var(--el-bg-color);
    border-radius: var(--el-border-radius-base);
    padding: 16px;

    .table-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .toolbar-left {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .toolbar-right {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }

    .table-pagination {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
    }

    :deep(.el-table) {
      // 表格内容过长时显示省略号
      .el-table__cell {
        .cell {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
</style>
